package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addFriend(Long userId1, Long userId2) {
        //1. 如果userId1没有好友userId2，则给userId1添加好友userId2
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId1).and("friendId").is(userId2));
        boolean exists = mongoTemplate.exists(query, Friend.class);
        if (!exists) {
            Friend friend = new Friend();
            friend.setUserId(userId1);
            friend.setFriendId(userId2);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }

        //2. 如果userId2没有好友userId1，则给userId2添加好友userId1
        query = new Query();
        query.addCriteria(Criteria.where("friendId").is(userId1).and("userId").is(userId2));
        exists = mongoTemplate.exists(query, Friend.class);
        if (!exists) {
            Friend friend = new Friend();
            friend.setUserId(userId2);
            friend.setFriendId(userId1);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }
    }

    @Override
    public PageResult findFriendList(Long userId, int page, int pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);

        return new PageResult((int) count, pagesize, pages, page, friendList);
    }

    @Override
    public void deleteById(Long userId, Long fansId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(fansId));
        mongoTemplate.remove(query, Friend.class);
        query = new Query(Criteria.where("userId").is(fansId).and("friendId").is(fansId));
        mongoTemplate.remove(query, Friend.class);
    }
}